#-*- coding:utf-8 -*-
'''
将一个pdf文档拆分pdf文档到多个文档
'''
import os
import sys
from datetime import datetime as dt
from ShortMessage import alert_module_pyMuPDF
from ShortMessage import MSG,test_file_exists,message_finished,message_started
from ArgumentParse import getSplitPdfParseResult,getMakePrintablePdfParseResult
from UtilFunction import getPageRange
FITZ_IMPORT_FAIL = False
try:
    import fitz 
except:
    FITZ_IMPORT_FAIL =True

def muSplitPdfFile(str_input,str_output,start_page,end_page,cover_page):
    message_started("START SPLITING")
    doc = muSplitPdfObject(str_input,start_page,end_page,cover_page)
    try:
        doc.save(str_output)
        MSG("Save To PDF [%s]"%str_output)
    except:
        MSG("Fail When Save File [%s]"%str_output)
    message_finished()
def muSplitPdfObject(input_pdf,start_page,end_page,cover_page):
    if type(input_pdf)== type(""):
        input_pdf = fitz.open(input_pdf)
    src_width,src_height = input_pdf[0].rect.width,input_pdf[0].rect.height
    src_rect = input_pdf[0].rect
    if end_page == -1:
        end_page = input_pdf.pageCount-1
    out_pdf = fitz.Document(width=src_width,height=src_height)
    if cover_page != -1:
        out_pg = out_pdf.newPage(width=src_width,height=src_height)
        out_pg.showPDFpage(src_rect,input_pdf,cover_page-1)
        out_pdf.newPage(width=src_width,height=src_height)#插入空白页
    for pg in range(start_page,end_page+1):
        out_pg = out_pdf.newPage(width=src_width,height=src_height)
        out_pg.showPDFpage(src_rect,input_pdf,pg)
    return out_pdf
if __name__ == "__main__":
    if FITZ_IMPORT_FAIL:
        alert_module_pyMuPDF()
        exit()
    result = getSplitPdfParseResult(sys.argv)
    if test_file_exists(result.input_pdf):
        select_pages,wholeBook = getPageRange(result.range_list,result.split_list)
        if wholeBook:#处理整本书，则取消处理
            MSG("")
        else:
            output_base_name = ""
            if result.output_pdf:
                output_base_name = os.path.join(os.getcwd(),result.output_pdf[:-4])
            else:
                output_base_name = result.input_pdf[:-4]
            for rg in select_pages:
                muSplitPdfFile(result.input_pdf,"%s_%s-%s_result.pdf"%(output_base_name,rg[0]+1,rg[1]+1),rg[0],rg[1],result.cover_page)
    